/**
 * @author zjkermit
 * @email zjkermit@gmail.com
 * @date Mar 10, 2014
 */
package zhoujian.oj.leetcode;

import org.junit.Test;

/**
 * @version 1.0
 * @description You are given an n x n 2D matrix representing an image.
 * 
 *              Rotate the image by 90 degrees (clockwise).
 * 
 *              Follow up: Could you do this in-place?
 */
public class RotateImage {

	public void rotate(int[][] matrix) {
		for (int i = 0; i < matrix.length / 2; i++) {
			swap(matrix, i, matrix.length - 1 - i);
		}
	}

	private void swap(int[][] matrix, int first, int last) {
		for (int i = first; i < last; i++) {
			int offset = i - first;
			int top = matrix[first][i];
			// left -> top
			matrix[first][i] = matrix[last - offset][first];
			// bottom -> left
			matrix[last - offset][first] = matrix[last][last - offset];
			// right -> bottom
			matrix[last][last - offset] = matrix[i][last];
			// top -> right
			matrix[i][last] = top;
		}
	}

	public void printMatrix(int[][] matrix) {
		for (int i = 0; i < matrix.length; i++) {
			for (int j = 0; j < matrix.length; j++) {
				System.out.print(matrix[i][j] + " ");
			}
			System.out.println();
		}
	}

	@Test
	public void test() {
		int[][] matrix = new int[][] { {1,2,3}, {4,5,6}, {7,8,9} };
		printMatrix(matrix);
		rotate(matrix);
		printMatrix(matrix);
	}
}
